package com.gp.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.gp.auth.AuthCredential;
import com.gp.auth.AuthenticationManager;
import com.gp.auth.AuthorizationManager;
import com.gp.auth.DefaultDataBaseProviderManager;
import com.gp.common.result.JsonResult;
import com.gp.common.utils.CookieUtils;
import com.gp.model.entity.BaseLoginLogs;
import com.gp.model.entity.BaseUser;
import com.gp.service.IBaseLoginLogsService;

/**
 * @author: 弓成龙
 * @date : 2017年11月26日
 * @email : gcx909109@sina.cn
 * @description: 登录控制器
 */
@RestController
public class LoginController extends BaseController {

	@Autowired
	private AuthenticationManager authenticationManager;
	@Autowired
	private AuthorizationManager authorizationManager;
	@Autowired
	DefaultDataBaseProviderManager defaultDataBaseProviderManager;
	@Autowired
	IBaseLoginLogsService loginLogService;

	@RequestMapping(value="/login",method=RequestMethod.POST)
	public JsonResult userLogin(String username, String password,@RequestParam(value="userType",required=false) String userType, HttpServletRequest request) { 
		// 进行认证
		AuthCredential credential = new AuthCredential(username, password,userType);
		BaseUser user = (BaseUser)defaultDataBaseProviderManager.getAuthenticationUserInfo(credential);
//		BaseUser user = (BaseUser) authenticationManager.doAuthenticateUser(credential, defaultDataBaseProviderManager);
		if (user != null) {
		    CookieUtils.setUser(request,user);
			// 认证成功后进行授权
			authorizationManager.doAuthorizateUser(user, request);
			// 插入用户登录日志
			BaseLoginLogs entity = new BaseLoginLogs(user.getId(),user.getNickName(),CookieUtils.getIpAddr(request),CookieUtils.getBrowser(request));
			loginLogService.insert(entity);
			user.setLoginPassword("");
			return renderSuccess("认证成功",user);
		} else {
			return renderError("用户认证失败");
		}
	}
	
	@RequestMapping(value="/outLogin",method=RequestMethod.POST)
    public JsonResult outLogin(HttpServletRequest request) { 
	  if(CookieUtils.isExistsCurrentUser(request)) {
            CookieUtils.removeUser(request);
            return renderSuccess("已经退出");
        } else {
            return renderError("尚未登录");
        }
    }
}
